package com.yidushishizijie;


/*
* 两线程，操作初始值为零的的一个变量，
* 实现一个线程对该变量加1，一个线程对该变量减1
* 实现交替，来十轮；
* */

public class ThreadWaitNotifyDemo {
    public static void main(String[] args) {
        AirConditioner airConditioner = new AirConditioner();
        new Thread(() ->{
            for (int i = 0; i < 10; i++) {
                try {
                    airConditioner.increase();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    airConditioner.decrease();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();
    }
}

class AirConditioner{
    private int number = 0;

    public synchronized void increase() throws InterruptedException {
        //判断
        while(number != 0){
            this.wait();
        }
        //干活
        number++;
        System.out.println(Thread.currentThread().getName()+"\t"+number);
        //通知
        this.notifyAll();
    }

    public synchronized void decrease() throws InterruptedException {
        //判断
        while(number == 0){
            this.wait();
        }
        //干活
        number--;
        System.out.println(Thread.currentThread().getName()+"\t"+number);
        //通知
        this.notifyAll();
    }
}
